/*
 * Copyright 2012-2022 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.boot.task;

import java.time.Duration;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;

import org.springframework.beans.BeanUtils;
import org.springframework.boot.context.properties.PropertyMapper;
import org.springframework.core.task.TaskDecorator;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

/**
 * 用于配置和创建 {@link TaskExecutor} 的构建器。提供设置常用 {@link ThreadPoolTaskExecutor} 配置和注册
 * {@link #taskDecorator(TaskDecorator)} 的便捷方法。对于高级配置，建议使用 {@link TaskExecutorCustomizer}。
 * <p>
 * 在典型的 Spring Boot 自动配置应用中，此构建器作为一个 bean 提供，
 * 并且可以在需要 {@link TaskExecutor} 时注入使用。
 *
 * @author Stephane Nicoll
 * @author Filip Hrisafov
 * @since 2.1.0
 */
public class TaskExecutorBuilder {

	private final Integer queueCapacity;

	private final Integer corePoolSize;

	private final Integer maxPoolSize;

	private final Boolean allowCoreThreadTimeOut;

	private final Duration keepAlive;

	private final Boolean awaitTermination;

	private final Duration awaitTerminationPeriod;

	private final String threadNamePrefix;

	private final TaskDecorator taskDecorator;

	private final Set<TaskExecutorCustomizer> customizers;

	public TaskExecutorBuilder() {
		this.queueCapacity = null;
		this.corePoolSize = null;
		this.maxPoolSize = null;
		this.allowCoreThreadTimeOut = null;
		this.keepAlive = null;
		this.awaitTermination = null;
		this.awaitTerminationPeriod = null;
		this.threadNamePrefix = null;
		this.taskDecorator = null;
		this.customizers = null;
	}

	private TaskExecutorBuilder(Integer queueCapacity, Integer corePoolSize, Integer maxPoolSize,
			Boolean allowCoreThreadTimeOut, Duration keepAlive, Boolean awaitTermination,
			Duration awaitTerminationPeriod, String threadNamePrefix, TaskDecorator taskDecorator,
			Set<TaskExecutorCustomizer> customizers) {
		this.queueCapacity = queueCapacity;
		this.corePoolSize = corePoolSize;
		this.maxPoolSize = maxPoolSize;
		this.allowCoreThreadTimeOut = allowCoreThreadTimeOut;
		this.keepAlive = keepAlive;
		this.awaitTermination = awaitTermination;
		this.awaitTerminationPeriod = awaitTerminationPeriod;
		this.threadNamePrefix = threadNamePrefix;
		this.taskDecorator = taskDecorator;
		this.customizers = customizers;
	}

	/**
	 * 设置队列容量。无界队列容量不会增加线程池大小，因此会忽略 {@link #maxPoolSize(int) maxPoolSize}。
	 * @param queueCapacity 要设置的队列容量
	 * @return 一个新的构建器实例
	 */
	public TaskExecutorBuilder queueCapacity(int queueCapacity) {
		return new TaskExecutorBuilder(queueCapacity, this.corePoolSize, this.maxPoolSize, this.allowCoreThreadTimeOut,
				this.keepAlive, this.awaitTermination, this.awaitTerminationPeriod, this.threadNamePrefix,
				this.taskDecorator, this.customizers);
	}

	/**
	 * 设置核心线程数。只要队列未满，核心线程数即为最大线程数。
	 * <p>
	 * 如果启用了 {@link #allowCoreThreadTimeOut(boolean)}，核心线程数可以动态增长和收缩。
	 * @param corePoolSize 要设置的核心线程池大小
	 * @return 一个新的构建器实例
	 */
	public TaskExecutorBuilder corePoolSize(int corePoolSize) {
		return new TaskExecutorBuilder(this.queueCapacity, corePoolSize, this.maxPoolSize, this.allowCoreThreadTimeOut,
				this.keepAlive, this.awaitTermination, this.awaitTerminationPeriod, this.threadNamePrefix,
				this.taskDecorator, this.customizers);
	}

	/**
	 * 设置允许的最大线程数。当 {@link #queueCapacity(int) 队列} 已满时，线程池可扩展至该大小以适应负载。
	 * <p>
	 * 如果 {@link #queueCapacity(int) 队列容量} 是无界的，则此设置被忽略。
	 * @param maxPoolSize 要设置的最大线程池大小
	 * @return 一个新的构建器实例
	 */
	public TaskExecutorBuilder maxPoolSize(int maxPoolSize) {
		return new TaskExecutorBuilder(this.queueCapacity, this.corePoolSize, maxPoolSize, this.allowCoreThreadTimeOut,
				this.keepAlive, this.awaitTermination, this.awaitTerminationPeriod, this.threadNamePrefix,
				this.taskDecorator, this.customizers);
	}

	/**
	 * 设置是否允许核心线程超时。当启用时，线程池可以动态增长和收缩。
	 * @param allowCoreThreadTimeOut 是否允许核心线程超时
	 * @return 一个新的构建器实例
	 */
	public TaskExecutorBuilder allowCoreThreadTimeOut(boolean allowCoreThreadTimeOut) {
		return new TaskExecutorBuilder(this.queueCapacity, this.corePoolSize, this.maxPoolSize, allowCoreThreadTimeOut,
				this.keepAlive, this.awaitTermination, this.awaitTerminationPeriod, this.threadNamePrefix,
				this.taskDecorator, this.customizers);
	}

	/**
	 * 设置线程在被终止前可以保持空闲的时间限制。
	 * @param keepAlive 要设置的保持活动时间
	 * @return 一个新的构建器实例
	 */
	public TaskExecutorBuilder keepAlive(Duration keepAlive) {
		return new TaskExecutorBuilder(this.queueCapacity, this.corePoolSize, this.maxPoolSize,
				this.allowCoreThreadTimeOut, keepAlive, this.awaitTermination, this.awaitTerminationPeriod,
				this.threadNamePrefix, this.taskDecorator, this.customizers);
	}

	/**
	 * 设置执行器在关闭时是否应等待已调度任务完成，
	 * 不中断正在运行的任务，并执行队列中的所有任务。
	 * @param awaitTermination 是否在关闭时等待任务完成
	 * @return 一个新的构建器实例
	 * @see #awaitTerminationPeriod(Duration)
	 */
	public TaskExecutorBuilder awaitTermination(boolean awaitTermination) {
		return new TaskExecutorBuilder(this.queueCapacity, this.corePoolSize, this.maxPoolSize,
				this.allowCoreThreadTimeOut, this.keepAlive, awaitTermination, this.awaitTerminationPeriod,
				this.threadNamePrefix, this.taskDecorator, this.customizers);
	}

	/**
	 * 设置执行器在关闭时阻塞的最长时间。
	 * 设置后，执行器在关闭时会阻塞，等待剩余任务完成执行，
	 * 然后容器的其余部分才会继续关闭。
	 * 这对于剩余任务可能需要访问容器管理的其他资源时尤其有用。
	 * @param awaitTerminationPeriod 要设置的等待终止时间
	 * @return 一个新的构建器实例
	 */
	public TaskExecutorBuilder awaitTerminationPeriod(Duration awaitTerminationPeriod) {
		return new TaskExecutorBuilder(this.queueCapacity, this.corePoolSize, this.maxPoolSize,
				this.allowCoreThreadTimeOut, this.keepAlive, this.awaitTermination, awaitTerminationPeriod,
				this.threadNamePrefix, this.taskDecorator, this.customizers);
	}

	/**
	 * 设置新创建线程名称的前缀。
	 * @param threadNamePrefix 要设置的线程名前缀
	 * @return 一个新的构建器实例
	 */
	public TaskExecutorBuilder threadNamePrefix(String threadNamePrefix) {
		return new TaskExecutorBuilder(this.queueCapacity, this.corePoolSize, this.maxPoolSize,
				this.allowCoreThreadTimeOut, this.keepAlive, this.awaitTermination, this.awaitTerminationPeriod,
				threadNamePrefix, this.taskDecorator, this.customizers);
	}

	/**
	 * 设置要使用的 {@link TaskDecorator}，或者设置为 {@code null} 表示不使用任何装饰器。
	 * @param taskDecorator 要使用的任务装饰器
	 * @return 一个新的构建器实例
	 */
	public TaskExecutorBuilder taskDecorator(TaskDecorator taskDecorator) {
		return new TaskExecutorBuilder(this.queueCapacity, this.corePoolSize, this.maxPoolSize,
				this.allowCoreThreadTimeOut, this.keepAlive, this.awaitTermination, this.awaitTerminationPeriod,
				this.threadNamePrefix, taskDecorator, this.customizers);
	}

	/**
	 * 设置应该应用于 {@link ThreadPoolTaskExecutor} 的 {@link TaskExecutorCustomizer TaskExecutorCustomizers}。
	 * Customizers 会按照添加的顺序，在构建器配置应用后执行。设置此值将替换之前配置的所有 Customizers。
	 * @param customizers 要设置的 Customizers
	 * @return 一个新的构建器实例
	 * @see #additionalCustomizers(TaskExecutorCustomizer...)
	 */
	public TaskExecutorBuilder customizers(TaskExecutorCustomizer... customizers) {
		Assert.notNull(customizers, "Customizers must not be null");
		return customizers(Arrays.asList(customizers));
	}

	/**
	 * 设置应该应用于 {@link ThreadPoolTaskExecutor} 的 {@link TaskExecutorCustomizer TaskExecutorCustomizers}。
	 * Customizers 会按照添加的顺序，在构建器配置应用后执行。设置此值将替换之前配置的所有 Customizers。
	 * @param customizers 要设置的 Customizers
	 * @return 一个新的构建器实例
	 * @see #additionalCustomizers(TaskExecutorCustomizer...)
	 */
	public TaskExecutorBuilder customizers(Iterable<TaskExecutorCustomizer> customizers) {
		Assert.notNull(customizers, "Customizers must not be null");
		return new TaskExecutorBuilder(this.queueCapacity, this.corePoolSize, this.maxPoolSize,
				this.allowCoreThreadTimeOut, this.keepAlive, this.awaitTermination, this.awaitTerminationPeriod,
				this.threadNamePrefix, this.taskDecorator, append(null, customizers));
	}

	/**
	 * 添加应该应用于 {@link ThreadPoolTaskExecutor} 的 {@link TaskExecutorCustomizer TaskExecutorCustomizers}。
	 * Customizers 会按照添加的顺序，在构建器配置应用后执行。
	 * @param customizers 要添加的 Customizers
	 * @return 一个新的构建器实例
	 * @see #customizers(TaskExecutorCustomizer...)
	 */
	public TaskExecutorBuilder additionalCustomizers(TaskExecutorCustomizer... customizers) {
		Assert.notNull(customizers, "Customizers must not be null");
		return additionalCustomizers(Arrays.asList(customizers));
	}

	/**
	 * 添加应该应用于 {@link ThreadPoolTaskExecutor} 的 {@link TaskExecutorCustomizer TaskExecutorCustomizers}。
	 * Customizers 会按照添加的顺序，在构建器配置应用后执行。
	 * @param customizers 要添加的 Customizers
	 * @return 一个新的构建器实例
	 * @see #customizers(TaskExecutorCustomizer...)
	 */
	public TaskExecutorBuilder additionalCustomizers(Iterable<TaskExecutorCustomizer> customizers) {
		Assert.notNull(customizers, "Customizers must not be null");
		return new TaskExecutorBuilder(this.queueCapacity, this.corePoolSize, this.maxPoolSize,
				this.allowCoreThreadTimeOut, this.keepAlive, this.awaitTermination, this.awaitTerminationPeriod,
				this.threadNamePrefix, this.taskDecorator, append(this.customizers, customizers));
	}

	/**
	 * 构建一个新的 {@link ThreadPoolTaskExecutor} 实例，并使用此构建器进行配置。
	 * @return 一个已配置的 {@link ThreadPoolTaskExecutor} 实例。
	 * @see #build(Class)
	 * @see #configure(ThreadPoolTaskExecutor)
	 */
	public ThreadPoolTaskExecutor build() {
		return configure(new ThreadPoolTaskExecutor());
	}

	/**
	 * 构建一个指定类型的新的 {@link ThreadPoolTaskExecutor} 实例，并使用此构建器进行配置。
	 * @param <T> 任务执行器的类型
	 * @param taskExecutorClass 要创建的模板类型
	 * @return 一个已配置的 {@link ThreadPoolTaskExecutor} 实例。
	 * @see #build()
	 * @see #configure(ThreadPoolTaskExecutor)
	 */
	public <T extends ThreadPoolTaskExecutor> T build(Class<T> taskExecutorClass) {
		return configure(BeanUtils.instantiateClass(taskExecutorClass));
	}

	/**
	 * 使用此构建器配置提供的 {@link ThreadPoolTaskExecutor} 实例。
	 * @param <T> 任务执行器的类型
	 * @param taskExecutor 要配置的 {@link ThreadPoolTaskExecutor} 实例
	 * @return 已配置的任务执行器实例
	 * @see #build()
	 * @see #build(Class)
	 */
	public <T extends ThreadPoolTaskExecutor> T configure(T taskExecutor) {
		PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull();
		map.from(this.queueCapacity).to(taskExecutor::setQueueCapacity);
		map.from(this.corePoolSize).to(taskExecutor::setCorePoolSize);
		map.from(this.maxPoolSize).to(taskExecutor::setMaxPoolSize);
		map.from(this.keepAlive).asInt(Duration::getSeconds).to(taskExecutor::setKeepAliveSeconds);
		map.from(this.allowCoreThreadTimeOut).to(taskExecutor::setAllowCoreThreadTimeOut);
		map.from(this.awaitTermination).to(taskExecutor::setWaitForTasksToCompleteOnShutdown);
		map.from(this.awaitTerminationPeriod).as(Duration::toMillis).to(taskExecutor::setAwaitTerminationMillis);
		map.from(this.threadNamePrefix).whenHasText().to(taskExecutor::setThreadNamePrefix);
		map.from(this.taskDecorator).to(taskExecutor::setTaskDecorator);
		if (!CollectionUtils.isEmpty(this.customizers)) {
			this.customizers.forEach((customizer) -> customizer.customize(taskExecutor));
		}
		return taskExecutor;
	}

	private <T> Set<T> append(Set<T> set, Iterable<? extends T> additions) {
		Set<T> result = new LinkedHashSet<>((set != null) ? set : Collections.emptySet());
		additions.forEach(result::add);
		return Collections.unmodifiableSet(result);
	}

}
